package org.example.completed.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.completed.domain.Order;
import org.example.completed.domain.Product;
import org.example.completed.domain.User;
import org.example.completed.mapper.OrderMapper;
import org.example.completed.mapper.ProductMapper;
import org.example.completed.model.vo.ResultVO;
import org.example.completed.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.example.completed.mapper.UserMapper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-04-02
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addOrder(Order order) {
        this.save(order);
    }

    @Override
    public int deleteOrder(String id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int updateOrder(Order order) {
        return baseMapper.updateById(order);
    }

    @Override
    public Order getOrderById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<Order> getAllOrders() {
        return baseMapper.selectList(null);
    }

    @Override
    @Transactional
    public ResultVO<Boolean> buyPet(String userId, String productId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return ResultVO.fail("用户不存在");
        }
        Product product = productMapper.selectById(productId);
        if (product == null || product.getStock() <= 0) {
            return ResultVO.fail("商品不存在或商品目前库存为空");
        }
        BigDecimal userMoney = user.getMoney();
        if (userMoney.compareTo(product.getPrice()) < 0) {
            return ResultVO.fail("用户余额不足");
        }
        if (productMapper.decreaseStock(productId) == 0) {
            return ResultVO.fail("商品库存不足");
        }
        BigDecimal newMoney = userMoney.subtract(product.getPrice());
        user.setMoney(newMoney);
        userMapper.updateMoney(user);
        Order order = new Order();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setPrice(product.getPrice());
        order.setStatus("1");
        order.setCreateTime(LocalDateTime.now());
        orderMapper.insert(order);

        return ResultVO.ok(true);
    }
}
